﻿
using DongFangGuoKai.WCSPlatform.WebApi.Utils;
using S7.Net;

namespace DongFangGuoKai.WCSPlatform.WebApi.HostService
{
    public class InitPlcHosetService : BackgroundService
    {
        private readonly Plc plc;
        private readonly PlcHeartbeatTool plcHeartbeatTool;
        private readonly ILogger<InitPlcHosetService> logger;

        public InitPlcHosetService(Plc plc,PlcHeartbeatTool plcHeartbeatTool,ILogger<InitPlcHosetService> logger)
        {
            this.plc = plc;
            this.plcHeartbeatTool = plcHeartbeatTool;
            this.logger = logger;
        }

        protected override Task ExecuteAsync(CancellationToken stoppingToken)
        {
          
            try
            {
                plc.Open();
                while (plc.IsConnected == false)
                {
                    plc.Open();
                    Task.Delay(1000);
                }
                plcHeartbeatTool.StartHeartbeat();
                logger.LogInformation("WCS程序启动成功");
            }
            catch (Exception ex)
            {
                logger.LogError("WCS程序失败:"+ex.Message);
                throw;
            }
            StopAsync(stoppingToken);


            return Task.CompletedTask;
        }
        public override Task StopAsync(CancellationToken cancellationToken)
        {
            Dispose();
            logger.LogInformation("Plc已成连接,InitPlcHosetService已释放");
            return base.StopAsync(cancellationToken);
        }
    }
}
